<?php

/**
 * AdController - The default controller class
 *
 * @author
 * @version
 */

require_once 'Zend/Controller/Action.php';

class GameController extends Zend_Controller_Action
{
	//FACEBOOK APP KEY
	protected $FACEBOOK_CONSUMER_ID = 0;
	//FACEBOOK密钥
	protected $FACEBOOK_CONSUMER_SECRET = '';
	//图片数组
	protected $Pictures = array();
	//最大参与用户数
	protected $MaxJoin = 0;
	//剩余参与用户数
	protected $MaxJoinLeft = 0;
	//结束时间
	protected $EndingTime = '';
	//最大likes数
	protected $MaxLikes = 0;
	//剩余likes数
	protected $MaxLikesLeft = 0;
	//提示信息
	protected $TipMsg = '';
	//活动开始
	protected $AppOn = 0;
	//1分享活动和2传销活动切换
	protected static $AppType = 1;
	//
	protected static $GameType = 0;
	//
	protected $MaxLikesBaseMan;
	
	public $inv = 0;
	public $itemid = 0;
	static $lockstream = 'st=lDEFABCNOPyzghijQRSTUwxkVWXYZabcdefIJK67nopqr89LMmGH012345uv';
	

    public function init()
    {
    	$this->_loadConfig();
//    	if($this->AppOn == 0)
//    		die('game not yet start!');
//    	$a = $this->_request->getActionName();
//    	if($a != 'joinfromad' && $a != 'gamestop') {
//    		$this->_isstop();
//    	}
		if (isset($_GET['i'])) {
			$_GET['i'] = $this->deCrypt($_GET['i']);
		}
		
    	if (isset($_GET['f'])) {
    		$params = $this->getRequest()->getParams();
    		if ($params['action'] != 'selectfriends') {
				$_GET['f'] = $this->deCrypt($_GET['f']);
    		}
		}
    }
    
    
    public function enCrypt($txtStream,$password = 'bestcheapjerseydeal')
    {
        //随机找一个数字，并从密锁串中找到一个密锁值
        $lockLen = strlen(self::$lockstream);
        $lockCount = rand(0,$lockLen-1);
        $randomLock = self::$lockstream[$lockCount];
        //结合随机密锁值生成MD5后的密码
        $password = md5($password.$randomLock);
        //开始对字符串加密
        $txtStream = base64_encode($txtStream);
        $tmpStream = '';
        $i=0;$j=0;$k = 0;
        for ($i=0; $i<strlen($txtStream); $i++) {
            $k = $k == strlen($password) ? 0 : $k;
            $j = (strpos(self::$lockstream,$txtStream[$i])+$lockCount+ord($password[$k]))%($lockLen);
            $tmpStream .= self::$lockstream[$j];
            $k++;
        }
        return rawurlencode($tmpStream.$randomLock);
    }
    
    public function deCrypt($txtStream,$password = 'bestcheapjerseydeal')
    {
        $lockLen = strlen(self::$lockstream);
        //获得字符串长度
        $txtLen = strlen($txtStream);
        //截取随机密锁值
        $randomLock = $txtStream[$txtLen - 1];
        //获得随机密码值的位置
        $lockCount = strpos(self::$lockstream,$randomLock);
        //结合随机密锁值生成MD5后的密码
        $password = md5($password.$randomLock);
        //开始对字符串解密
        $txtStream = substr($txtStream,0,$txtLen-1);
        $tmpStream = '';
        $i=0;$j=0;$k = 0;
        for ($i=0; $i<strlen($txtStream); $i++) {
            $k = $k == strlen($password) ? 0 : $k;
            $j = strpos(self::$lockstream,$txtStream[$i]) - $lockCount - ord($password[$k]);
            while($j < 0){
                $j = $j + ($lockLen);
            }
            $tmpStream .= self::$lockstream[$j];
            $k++;
        }
        return base64_decode($tmpStream);
    }
    
    public function testAction()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$params = $this->getRequest()->getParams();
		$str = '12345678';
		$encode = $this->enCrypt($str);
		$decode = $this->deCrypt('RMMNj8MvarEK2eCn1Lv62');
		echo $encode . "<br/>";
		echo $decode;
    }

    public function preDispatch()
    {
        $this->view->addHelperPath(MY_ROOT.'/vhelpers');
        Zend_Controller_Action_HelperBroker::addPath(MY_ROOT.'/chelpers');
        $this->getHelper('layout')->setLayout('gamelayout');
    }
    
    /**
     * 通过验证返回活动主页
     */
    public function indexAction()
    {
//		$this->_auth();
		if(isset($_COOKIE[COOKIE_PRE.'joinfrom_ad'])) {
			setcookie(COOKIE_PRE.'joinfrom_ad','',time()-3600,'/');
		}
		$email = $_COOKIE[COOKIE_PRE.'joinfrom_email'];
		$params = $this->getRequest()->getParams();
		unset($params['f']);
		$this->view->params = http_build_query($params);
		$this->view->signed_request = $_REQUEST['signed_request'];
		if(isset($email)){
			$email = urldecode($email);
			$m_game = new CGame();
			$fbme_id = $this->_getcuruser();
			try{
				if($m_game->IsJoin($fbme_id)) {
					throw new Exception('You have joined.');
				}
				if(!(strlen ( $email ) > 4 && preg_match ( "/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email ))) {
					throw new Exception('The email is not correct!');
				}
				if($m_game->GetJoinerCounts() >= $this->MaxJoin){
					throw new Exception('Sorry. The game is over.');
				}
			}catch(Exception $e){
				setcookie(COOKIE_PRE.'joinfrom_email','',time()-3600,'/');
				$this->_redirect('/game-error?errorMsg='.urlencode($e->getMessage()));
				exit();
			}
			try{
				$insert_data = array('joineremail'=>$email,'jointime'=>time(),'facebookid'=>$fbme_id,'gametype'=>self::$GameType);
				$m_game->Join($insert_data);
				setcookie(COOKIE_PRE.'joinfrom_email','',time()-3600,'/');
			}catch(Exception $e){}
		}
		$this->view->f = $this->_request->getParam('f',0);
    	if(self::$AppType == 2)
			$this->view->link = '/game-redirect?i=' . $this->enCrypt($this->_getCurrentUser()) . '&' . $this->view->params . '&itemid=';
    	if($this->view->f > 0 && self::$AppType == 2)
			$this->view->link = '/game-redirect?i=' . $this->enCrypt($this->view->f) . '&' . $this->view->params . '&itemid=';
		$this->view->pictures = $this->Pictures;
    }
    
    /**
     * 通过验证选择朋友
     */
    public function selectfriendsAction()
    {
    	error_reporting(1);
		$picid = intval($this->_request->getParam('picid',0));
		if($picid == 0)
			die('error');
		$pic = array();
		foreach ($this->Pictures as $p) {
			if($p['Picture_ID'] == $picid) {
				$pic = $p;
				break;
			}
		}
		if(empty($pic))
			die('error');
//		$page = ($this->_request->getParam('page',1) == 0) ? 1 : $this->_request->getParam('page',1);
//		$pagesize = 10;
		$this->_auth();
		$facebook = $this->_createFacebookObj();
		try{
			$fbme_id = $this->_getcuruser();//$session['uid']
			$fbmf = $facebook->api('/me/friends?fields=picture,name,id');
//			$pageArray = CFilter::filterPage ( $page, count($fbmf['data']), $pagesize );
//			$pageString = CPage::divPages( $pageArray ['pageNumber'], $pageArray ['page'], ROOT_PATH."/game-selectfriends?");
//			$fbmf_diaplsy = array();
//			$limit = ($page*$pagesize >= count($fbmf['data'])) ? count($fbmf['data']) : $page*$pagesize;
//			for ($i=($page-1)*$pagesize;$i<$limit;$i++)
//			{
//				$fbmf_diaplsy[] = $fbmf['data'][$i];
//			}
		} catch (Exception $e) {
			$this->_redirect('/game-error?loginurl='.urlencode($facebook->getLoginUrl()).'&err='.urlencode($e->getMessage()));
			exit();
		}
		$this->view->fbmf = $fbmf['data'];
		$this->view->pic = $pic;
		$this->view->f = $this->_request->getParam('f',0);
		if(self::$AppType == 2) {
			$this->view->link = '/game-redirect?i=' . $this->enCrypt($this->_getCurrentUser()) . '&itemid=';
			$this->view->sharelink = 'http://apps.facebook.com/sharejerseys/?i=' . $this->enCrypt($this->_getCurrentUser()) . '&itemid=';
		}
    	if($this->view->f > 0 && self::$AppType == 2)
			$this->view->link = '/game-redirect?i=' . $this->enCrypt($this->view->f) . '&itemid=';
//		$this->view->pageString = $pageString;
		$this->view->signed_request = isset($_REQUEST['signed_request']) ? $_REQUEST['signed_request'] : '';
    }
    
    /**
     * 通过验证-发送留言页
     */
    public function dosendmsgAction()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
//    	$picid = intval($this->_request->getParam('picid',0));
//		if($picid == 0)
//			die('Error picture id!');
		$facebook = $this->_createFacebookObj();
		$tip_msg = 'ok';
		if(isset($_POST['picurl'])) {
			$pic = array();
			foreach ($this->Pictures as $p) {
				if($p['Picture_Url'] == $_POST['picurl']) {
					$pic = $p;
					break;
				}
			}
			try{
//				$this->_auth();
				$me = $facebook->api('/'.$this->_getcuruser());
//				var_dump($me);exit;
				$data=array(
					"picture"=>$_POST['picurl'], 
					'link' => (self::$AppType == 1) ? 'http://www.facebook.com/goalshop/app_159404804162945' : 'http://apps.facebook.com/sharejerseys/?i='.$this->enCrypt($me['id']).'&itemid='.$pic['Picture_ID'],//http://apps.facebook.com/sharejerseys/
					'name' => $pic['Picture_Title'],
					'description'  => $pic['Picture_Description'],
					"message"=>$_POST['content'],
				);
				$facebook->api('/'.$_POST['postto'].'/feed',"POST",$data);
				//插入分享记录
				$m_share = new CPyramidMemberShare();
				$m_share->add(array('facebook_id'=>$me['id'],'to_facebook_id'=>$_POST['postto'],'from_facebook_id'=>$_POST['f'],'share_itemid'=>$pic['Picture_ID'],'add_time'=>time(),'email'=>$me['email'],'nickname'=>$me['name']));
			} catch (Exception $e) {
				$tip_msg = $e->getMessage();
			}
		}
		die($tip_msg);
//		$this->view->pic = $pic;
//		$this->view->tip_msg = $tip_msg;
/*		echo '<script>window.location.href="/game-join";</script>';*/
//	    return false;
    }
    
    /**
     * 用户加入活动
     */
    public function joinAction()
    {
		$params = $this->getRequest()->getParams();
		
		if (isset($params['i'])) {
			$params['i'] = $this->enCrypt($params['i']);
		}
		
    	if (isset($params['f'])) {
			$params['f'] = $this->enCrypt($params['f']);
		}
		
		$query = http_build_query($params);
		
		$i = $this->getRequest()->getParam('i', 0);
		$itemid = $this->getRequest()->getParam('itemid', 0);
		
    	if(self::$AppType != 1) {    		
			$this->_redirect('/game-sellindex?' . $query);
			return false;
    	}
    	/**不管了
		if(!empty($i) && !empty($itemid)) {
			$this->_forward('sellindex');
    		return;
			$this->_redirect('/game-sellindex?' . $query);
			return false;
		}
		*/
		
		$error = $this->_request->getParam('error','');
		if($error == 'access_denied'){
			//$this->_redirect('http://www.facebook.com/pages/soccerjerseyseller/283621108345431?sk=app_215453218539992');gshopad
			echo '<script>top.location.href="http://www.facebook.com/goalshop?sk=app_203794096380805";</script>';
			exit();
		}
		$this->_oauth();
    	if(isset($_COOKIE[COOKIE_PRE.'joinfrom_ad'])) {
    		$this->_redirect('http://www.bestcheapjerseydeal.com/game-index?' . $query);
	    	exit();
    	}
    	$this->_isstop();
    	$m_game = new CGame();
    	$this->view->uid = $this->_getcuruser();
    	$this->view->signed_request = $_REQUEST['signed_request'];
//    	$session = $this->_auth();
//    	if(!empty($man_obj)) {
	    	if($m_game->IsJoin($this->_getcuruser())) {
	    		$this->view->isjoin = 1;
	    		return false;
	    	} else {
//		    	$facebook = $this->_createFacebookObj();
//		    	try{
//					$man_obj = $facebook->api('/me?fields=email');
//					$this->view->man_obj = $man_obj;
//		    	}
//				catch (Exception $e) {
/*					echo '<script>window.location.href="/game-join";</script>';*/
//			    	exit();
//				}
	    	}
//    	}
    }
    
    /**
     * 用户加入活动
     */
    public function dojoinAction()
    {
    	$m_game = new CGame();
    	$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
//    	if($this->_request->getPost())
//    	{
//    		$session = $this->_auth();
		try{
    		$insert_data = array();
    		$email = $this->_request->getParam('email','');
    		$uid = $this->_request->getParam('uid','');
			if($m_game->IsJoin($uid)) {
    			throw new Exception('You have joined.');
    		}
    		if($email == '')
    			throw new Exception('You must input your email address!');
    		if(strlen ( $email ) > 6 && preg_match ( "/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email )) {
    			$insert_data = array('joineremail'=>$email,'jointime'=>time(),'facebookid'=>$uid,'gametype'=>self::$GameType);
    		} else {
    			throw new Exception('Sorry, please input the correct email address.');
    		}
    		if(!empty($insert_data))
    		{
	    			if($m_game->GetJoinerCounts() >= $this->MaxJoin){
						$error_msg = 'Sorry. The game is over.';
					}else{
						try{
							$m_game->Join($insert_data);
						} catch (Exception $e) {}
						die('ok');
						exit();
					}
    		}
		} catch (Exception $e) {
    		$error_msg = $e->getMessage();
    	}
    	die($error_msg);
//    	}
    }

    
    /**
     * 用户加入活动-从广告
     */
    public function joinfromadAction()
    {
//    	$m_game = new CGame();
//    	if(isset($_COOKIE[COOKIE_PRE.'joinfrom_ad'])) {
/*    		echo '<script>window.location.href="/game-index";</script>';*/
//	    	exit();
//    	}
//    	$session = $this->_auth();
//    	if(!empty($session['uid'])) {
//	    	if($m_game->IsJoin($session['uid'])) {
//	    		$this->view->isjoin = 1;
//	    		return false;
//	    	}
//    	}
		$share = $this->_request->getParam('share',0);
		if($share == 1) {
			setcookie(COOKIE_PRE.'joinfrom_ad',1,null,'/');
			$this->_redirect('http://apps.facebook.com/sharejerseys/');
		    exit();
		}
		$m_game = new CGame();
		$this->view->stop = 0;
		$this->view->maxjoin = 0;
    	if(($this->EndingTime - time()) <= 0) {
    		$this->view->stop = 1;
    	}
    	if($m_game->GetJoinerCounts() >= $this->MaxJoin) {
    		$this->view->maxjoin = 1;
    	}
		$error_msg = '';
		$email = $this->_request->getParam('email','');
		if($email) {
			setcookie(COOKIE_PRE.'joinfrom_ad',1,null,'/');
			setcookie(COOKIE_PRE.'joinfrom_email',urlencode($email),null,'/');
			$this->_redirect('http://apps.facebook.com/sharejerseys/');
			exit();
		}
    	$this->view->error_msg = $error_msg;
    }
    
    /**
     * 用户加入活动-从广告
     */
    public function joinfromadtwoAction()
    {
		$this->joinfromadAction();
    }
    
 
    /**
     * 用户likes
     */
    public function befansAction()
    {
    	$facebook=$this->_createFacebookObj();
    	$signed_request = $facebook->getSignedRequest();

		  if($signed_request = $this->parsePageSignedRequest()) {
		    if($signed_request->page->liked) {
		      $this->_redirect('/game-joinfromad');
			  exit();
		    }
		  }
//    	die();
//    	$this->_auth();
//    	if($this->_isFans()) {
/*    		echo '<script>window.location.href="/game-joinfromad";</script>';*/
//    		exit();
//    	}
    }
    
	public function parsePageSignedRequest() {
	    if (isset($_REQUEST['signed_request'])) {
	      $encoded_sig = null;
	      $payload = null;
	      list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
	      $sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
	      $data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
	      return $data;
	    }
	    return false;
	  }

    /**
     * 用户是否likes
     */
    public function isfansAction()
    {
    	if($this->_isFans())
    		echo 1;
    	else
    		echo 0;
    	exit;
    }
    
    /**
     * 活动结束
     */
    public function gamestopAction()
    {
    	$session = $this->_auth();
    	$m_game = new CGame();
    	$winner_list = $m_game->GetAllJoiners();
    	$this->view->iswinner = 0;
		$fbme_id = $this->_getcuruser();
		if($fbme_id > 0) {
    	if($winner = $m_game->IsJoin($fbme_id)) {
    		$this->view->iswinner = 1;
    		$hashcode = $m_game->genHashCode($winner['joineremail'], $winner['jointime'], $winner['facebookid']);
    		$this->view->hashCode = $hashcode;
    	}
		}
    	
    	$this->view->winner_list = $winner_list;
    }
    
    public function errorAction(){
		$errorMsg = urldecode($this->_request->getParam('errorMsg',''));
		$err = urldecode($this->_request->getParam('err',''));
    	$loginurl = urldecode($this->_request->getParam('loginurl',''));
    	$this->view->loginurl = $loginurl;
		$this->view->errorMsg = $errorMsg;
		$this->view->err = $err;
    }
    
    /**
     * 验证FACEBOOK
     */
    public function authAction()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$referer = $_SERVER['HTTP_REFERER'];
		if($referer == '') {
			echo '<script>alert("referer url is null!");window.history.go(-1);</script>';
			return false;
		}
		$facebook = $this->_createFacebookObj();
	    $this->_redirect($facebook->getLoginUrl(array('next'=>$referer,'req_perms' =>'email,user_birthday,status_update,publish_stream,user_photos,user_videos')));//,friend_photos//MY_URL.'/active-index'
    }
    
    /**
     * 加载活动配置
     */
    public function _loadConfig()
    {
		try{
			$config = new Zend_Config_Xml(MY_ROOT.'/html/upload/game/configs.xml');
			$config = $config->toArray();
		} catch (Exception $e) {
			die('error game configs');
		}
		if(empty($config))
			die('error game configs');
		//初始化配置
		$this->FACEBOOK_CONSUMER_ID = $config['FacebookInfo']['Facebook_Key'];
		$this->FACEBOOK_CONSUMER_SECRET = $config['FacebookInfo']['Facebook_Secret'];
		$this->MaxJoin = $this->view->MaxJoin = $config['MaxJoin'];
		$m_game = new CGame();
		$this->MaxJoinLeft = $this->view->MaxJoinLeft = $this->MaxJoin - $m_game->GetJoinerCounts();
		$this->MaxLikes = $this->view->MaxLikes = $config['MaxLikes'];
//    	$myCache=$this->_createCachObj(1800, '/cache/game/');
//		$result=$myCache->load('FB_MaxLikesLeft');
//		if(!$result){
			try {
				$likes_obj = file_get_contents('https://graph.facebook.com/'.$config['MaxLikesBaseMan']);
				$likes_obj = json_decode($likes_obj);
				$this->MaxLikesLeft = $this->view->MaxLikesLeft = $this->MaxLikes - ($likes_obj->likes - $config['MaxLikesBase']);
				if($this->MaxLikesLeft < 0)
					$this->MaxLikesLeft = $this->view->MaxLikesLeft = 0;
				if($this->MaxLikesLeft > $config['MaxLikes'])
					$this->MaxLikesLeft = $this->view->MaxLikesLeft = $config['MaxLikes'];
//				$myCache->save($this->MaxLikesLeft,'FB_MaxLikesLeft');
			} catch (Exception $e) {
				$facebook = $this->_createFacebookObj();
				$this->_redirect('/game-error?errmsg='.urldecode($facebook->getLoginUrl(array('next'=>'/game-index','req_perms' =>'publish_stream,user_photos'))));
				exit();
			}
//		}else{
//			$this->MaxLikesLeft = $this->view->MaxLikesLeft =  $result;
//		}
		$this->MaxLikesBaseMan = $config['MaxLikesBaseMan'];
		$this->EndingTime = $this->view->EndingTime = strtotime($config['EndingTime']);
		$this->AppOn = $config['AppOn'];
		$this->TipMsg = $config['TipMsg'];
		$this->Pictures = $config['Pictures']['Picture'];
    }
    
    /**
     * 创建FACEBOOK对象
     */
    private function _createFacebookObj()
    {
    	$facebook = new Facebook(array(
	    	'appId'  => $this->FACEBOOK_CONSUMER_ID,
	    	'secret' => $this->FACEBOOK_CONSUMER_SECRET, 
	    	'cookie' => true,
	    ));
	    return $facebook;
    }
    
    /**
     * 创建缓存对象
     */
    private function _createCachObj($lefttime = 3600, $cache_dir = '/cache/')
    {
    	Zend_Loader::loadClass('Zend_Cache');
		$frontendOptions = array(
		   'caching'=> true,
		   'lifeTime' => $lefttime,
		   'automatic_serialization' => true,
		);
		$backendOptions = array(
		    'cache_dir' => MY_ROOT.$cache_dir
		);
		$myCache = Zend_Cache::factory('Page', 'File', $frontendOptions, $backendOptions);
		return $myCache;
    }
    
    /**
     * 验证是否通过验证
     */
    private function _auth()
    {
    	$session = null;
    	$facebook = $this->_createFacebookObj();
    	$facebook->setCookieSupport(false);    	
		$session = $facebook->getSession();
		if(empty($session))
		{
			echo '<script>window.location.href=\''.$facebook->getLoginUrl(array('req_perms' =>'publish_stream,user_photos')).'\'</script>';
    		exit();
		}
		else {
//			$facebook->setSession($session);
			return $session;
		}
    }

    /**old
    private function _oauth() {
    	$canvas_page = "http://apps.facebook.com/sharejersey/";
	
	     $auth_url = "https://www.facebook.com/dialog/oauth?client_id=" 
	            . $this->FACEBOOK_CONSUMER_ID . "&redirect_uri=" . urlencode($canvas_page) . '&scope=publish_stream,user_photos';
	
	     $signed_request = $_REQUEST["signed_request"];
	
	     list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
	
	     $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
	
	     if (empty($data["user_id"])) {
	            echo("<script> top.location.href='" . $auth_url . "'</script>");
	            exit();
	     }
	     $_SESSION['current_fb_user'] = $data["user_id"];
//	     else {
//	            echo ("Welcome User: " . $data["user_id"]);
//	     }
//	     die();
    }*/
	
    
    /**
     * 判断是否为粉丝
     */
    private function _isFans()
    {
    	$facebook = $this->_createFacebookObj();
    	try {
    		$fans_obj = $facebook->api('/me/likes/'.$this->MaxLikesBaseMan);
    	} catch (Exception $e) {
			die($e);
		}
    	return (empty($fans_obj['data'])) ? false : true;
    }
    
    private function _getcuruser()
    {    	
    	return $_SESSION['current_fb_user'];
    }
    
    private function _isstop(){
    	if(($this->EndingTime - time()) <= 0) {
    		echo("<script> window.location.href='/game-gamestop'</script>");
	        exit();
    	}
    }
    
    /**
     * 领奖 URL:/game-prize?hash=hashCode
     */
    public function prizeAction()
    {    	
    	$this->getHelper('Nav')->getHeaderNav();
    	$this->getHelper('layout')->setLayout('layout');	
		$hash = $this->getRequest()->getParam('hash', '');
		if (empty($hash)) {
			echo 'You just clicked The wrong link.';
			exit();
		}
		$game = new CGame();
		if (!$game->isValidate($hash)) {
			$this->view->showMsg('You just clicked The wrong link.', '/');
			return;
		}
		setcookie(COOKIE_PRE.'prize_hash',$hash,null,'/');
		$member = new CMember();
    	if($member->isUser($this->_request->getModuleName(),$this->_request->getControllerName()) && $_COOKIE[COOKIE_PRE.'member_type'] == 'buyer') {
            $this->view->showMsg('You can get 2 jerseys for free', '/');
        } else {
        	$this->view->showMsg('Please sign in, then you can get 2 jersey for free', '/auth-login');
        }
    }
    
    /**
     * 传销开始
     */
	public function sellindexAction()
	{		
		$this->getHelper('layout')->disableLayout();
		
		$inv = $this->getRequest()->getParam('i', 0); //邀请人
		$params = $this->getRequest()->getParams();
		unset($params['i']);
		unset($params['itemid']);
		//unset($_SESSION['current_fb_user']);exit();
		$pattern = '/\d+/';		
		if(!empty($inv) && !preg_match($pattern, $inv)) {
			exit();
		}	
		if (empty($inv)) { //没有邀请人
			$renderView = 'sellindex';
		} else {
			$this->inv = $inv;			
			$itemid = $this->getRequest()->getParam('itemid', 0);
			$itemid = intval($itemid);			
			$this->itemid = $itemid;
			$config = new Zend_Config_Xml(MY_ROOT.'/html/upload/game/configs.xml');
			$config = $config->toArray();
			$this->view->img = '';
			foreach ($config['Pictures']['Picture'] as $v) {
				if ($v['Picture_ID'] == $itemid) {					
					$this->view->img = $v['Picture_Url'];										
				}
			}
			$this->view->link = '/game-redirect?i=' . $this->enCrypt($inv) . '&itemid=' . $itemid . '&' . http_build_query($params);
			$renderView = 'indexshare';
		}
		$this->view->shareLink = MY_URL . "/game-index/?f=" . $this->enCrypt($inv) . '&' . http_build_query($params);
		$this->_oauth();
		$currentUserId = $this->_getCurrentUser();	
		$this->view->currentUserId = $currentUserId;
		$memberModel = new CPyramidMember();
		
		$memberModel->add(array('facebook_id'=>$currentUserId, 'inviter_facebook_id'=>empty($inv)?0:$inv, 'add_time'=>time()));
		
		//分享信息
		$shareModel = new CPyramidMemberShare();
		
		$myShareCount = $shareModel->getMyShareCount($currentUserId);
		$friendsShareCount = $shareModel->getFriendsShareCount($currentUserId);
		
		//访问信息
		$visitModel = new CPyramidMemberVisit();
				
		$friendsVisitCount = $visitModel->getFriendsVisitCount($currentUserId);
		$interestedFriendsCount = $friendsVisitCount;
		
		//购买信息
		$buyModel = new CPyramidMemberBuy();		
		$myBuyAmount = $buyModel->getMyBuyAmount($currentUserId);
		$friendsBuyAmount = $buyModel->getFriendBuyAmount($currentUserId);
		$buyFriends = $buyModel->getCountBuyFriend($currentUserId);
		
		//佣金信息
		$accountDetailModel = new CPyramidAccountDetail();
		$profit = $accountDetailModel->getMyAmount($currentUserId);
		
		//现金账户
		$accountModel = new CPyramidMemberAccount();
		$cash = $accountModel->getMyCash($currentUserId);
		$rank = $accountModel->getRank($currentUserId);
	
		$this->view->myShareCount = $myShareCount;
		$this->view->friendsShareCount = $friendsShareCount;
		
		$this->view->friendsVisitCount = $friendsVisitCount;
		$this->view->interestedFriendsCount = $interestedFriendsCount;
		
		$this->view->myBuyAmount = $myBuyAmount;
		$this->view->friendsBuyAmount = $friendsBuyAmount;
		$this->view->buyFriends = $buyFriends;
		$this->view->profit = $profit;
		$this->view->rank = $rank;
		
		$this->view->cash = $cash;
		
		$this->render($renderView);
	}
	
	public function redirectAction()
	{
		$this->getHelper('layout')->disableLayout();
		$this->getHelper('viewRenderer')->setNoRender();
		
		$inv = $this->getRequest()->getParam('i', 0);		
		$itemid = $this->getRequest()->getParam('itemid', 0);
		
		$itemid = intval($itemid);
		
		$pattern = '/\d+/';
		
		if(empty($inv) || !preg_match($pattern, $inv)) {
			exit();
		}		
		
		if (empty($itemid)) {
			exit();
		}
		
		$currentUserId = $this->_getCurrentUser();
		
		setcookie(COOKIE_PRE.'inv_facebook_id', $inv, time()+3600*24*365, '/');
		setcookie(COOKIE_PRE.'my_facebook_id', $currentUserId, time()+3600*24*365, '/');
		
		$member = new CMember();
		if (!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer'){
	       
	    } else {
	    	 //登录
	        $row = array('my_facebook_id'=>$currentUserId, 'inv_facebook_id'=>$inv, 'add_time'=>time());        	
			$invModel = new CPyramidMemberInv();
			$invModel->add($row, $_COOKIE[COOKIE_PRE.'uid']);
	    }
		
		$visitModel = new CPyramidMemberVisit();
		$visitModel->add(array('facebook_id'=>$currentUserId, 'from_facebook_id'=>$inv, 'ip'=>$_SERVER['REMOTE_ADDR'], 'itemid'=>$itemid, 'add_time'=>time()));
		
		$this->_redirect('/pd-' . $itemid . '.html');
		//echo '<script>top.location.href="' . MY_URL . '/pd-' . $itemid . '.html";</script>';
	}
	
	public function adAction()
	{
		$this->getHelper('layout')->disableLayout();
		$this->view->link = 'http://apps.facebook.com/sharejerseys/';
	}
	
	public function cashAction()
	{
		$this->getHelper('layout')->disableLayout();
		$currentUserId = $this->_getCurrentUser();
		$email = $this->getRequest()->getParam('email', '');
		$amount = $this->getRequest()->getParam('amount', 0);
		
		$validator = new Zend_Validate_EmailAddress();

		if (!$validator->isValid($email)) {
			exit(0);
		}
		
		if (!preg_match('/^[^0]\d*(\.\d{2})?/', $amount)) {
			exit(1);
		}
		
		$accountModel = new CPyramidMemberAccount();
		$accountMount = $accountModel->getMyCash($currentUserId);
		
		if ($amount > $accountMount) {		
			echo 2;
			exit();
		}
		
		$cashModel = new CPyramidAccountCrash();
		$db = $accountModel->getAdapter();
		$db->beginTransaction();
		try {
			$cashModel->add(array('facebook_id'=>$currentUserId, 'amount'=>$amount, 'email'=>$email, 'add_time'=>time()));
			$accountModel->subAmount($amount, $currentUserId);
			$db->commit();
			echo 5;
			exit();
		} catch (Exception $e) {
			$db->rollBack();
			echo 3;
			exit();
		}
	}
	
	private function _oauth()
	{ 
    	$canvas_page = "https://apps.facebook.com/sharejerseys/?";
    	
    	if ($this->inv) {
    		$canvas_page .= 'i=' . $this->enCrypt($this->inv) . '&';
    	}
    	if ($this->itemid) {
    		$canvas_page .= 'itemid=' . $this->enCrypt($this->itemid) . '&';
    	}
    	
	    $auth_url = "https://www.facebook.com/dialog/oauth?client_id=" 
	            . $this->FACEBOOK_CONSUMER_ID . "&redirect_uri=" . urlencode($canvas_page) . '&scope=publish_stream,user_photos';
	    $signed_request = $_REQUEST["signed_request"];
	    list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
	    $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
	    if (empty($data["user_id"])) {
	            echo("<script> top.location.href='" . $auth_url . "'</script>");
	            exit();
	    }
	    $_SESSION['current_fb_user'] = $data["user_id"];	  
	    return $data["user_id"];   
    }
    
    protected function _getCurrentUser()
    {
    	if (isset($_SESSION['current_fb_user'])) {
			$currentUserId = $_SESSION['current_fb_user'];
		} else {
			$this->_oauth();
			$currentUserId = $_SESSION['current_fb_user'];
		}
		//$currentUserId = $this->_oauth();
		return $currentUserId;
    }
    
    public function clearAction()
    {
    	$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		unset($_SESSION['current_fb_user']);
    }
    
	public function dataAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		
		$detailModel = new CPyramidAccountDetail();
		$currentUserId = $this->getRequest()->getParam('u', 0);
		$today = date('Y-m-d', time());
		$firstDay = date('Y-m-d', time() - 3600*24*30);
		
		$dataRow = $detailModel->getMyData($today, $firstDay, $currentUserId);
		
		$dataArray = array();
		
		for ($i = 30; $i>=0; $i--) {
			$dataArray[] = date('m-d', time()-3600*24*$i);
		}
		
		$return = array();
		
		foreach ($dataArray as $v) {
			$return[$v] = 0;			
		}
		foreach ($dataRow as $v) {
			if (!empty($v['add_time'])) {
				$return[date('m-d', $v['add_time'])] += $v['sum_amount'];
			}
		}	
		
		$date = array_keys($return);
		$include = array_values($return);	
		
		include MY_ROOT . '/library/Flash/open-flash-chart.php'; 		 
		 
		$chart = new open_flash_chart(); 
		$chart->set_bg_colour('#FFFFFF');
				
		$titleStr = 'My earn';
		
		
//		$title = new title($titleStr); 
//		$title->set_style( "{font-size: 12px; text-align: center;}" ); 
//		$chart->set_title( $title ); 		
		
		 
		$area = new area(); 
		$area->set_colour( '#5B56B6' ); 
		$area->set_values( $include ); 		
		$area->set_key( 'Money:($)', 8 ); 
		$chart->add_element( $area ); 
		 
		$x_labels = new x_axis_labels(); 
		$x_labels->set_steps( 10 ); 
		$x_labels->set_vertical(); 
		$x_labels->rotate('0'); 
		$x_labels->set_colour( '#000000' ); 
		$x_labels->set_labels( $date ); 
		 
		$x = new x_axis(); 
		$x->set_colour( '#000000' ); 
		$x->set_grid_colour( '#acacac' ); 
		$x->set_offset( false ); 
		$x->set_steps(1); 
		// Add the X Axis Labels to the X Axis 
		$x->set_labels( $x_labels ); 
		 
		$chart->set_x_axis( $x ); 
		 
		// 
		// LOOK: 
		// 
		$x_legend = new x_legend(); 
		$x_legend->set_style( '{font-size: 100px; color: #000000}' ); 
		$chart->set_x_legend( $x_legend ); 
		 
		// 
		// remove this when the Y Axis is smarter 
		// 
		$y = new y_axis(); 
		$y->set_range( 0, max($include)+1, max($include) / 10); 
		$y->set_colour('#000000');
		$y->set_grid_colour('#dddddd'); 
		$y->set_steps( 100 ); 
		$chart->add_y_axis($y); 
		 
		echo $chart->toPrettyString(); 
	}
}
